import urllib
from whirlwind.core.request import BaseRequest
from tornado import locale
from application.models.user import User



class BasicHandler(BaseRequest):
    """
    Extend the BaseRequest handle. 
    Add locale settings.
    """
    def __init__(self, application, request):
        BaseRequest.__init__(self, application, request)

    def get_user_locale(self):
        """
        Get user locale
        """
        #return locale.get(self.session['locale'])
        return locale.get("zh_CN")

    def get_browser_locale(self):
        """
        Get browser locale
        """
        return locale.get("zh_CN")

    def get_current_user(self):
        if hasattr(self, '_current_user') and self._current_user:
            return self._current_user
        email = self.session['email']
        if email:
            return User.lookup(email)
        email_cookie = self.get_secure_cookie('email')
        if email_cookie:
            user = User.lookup(email_cookie)
            if user:
                self.session['username'] = user.username
                self.session['email'] = user._id
                self.session['locale'] = user.profile.locale
                self.set_current_user(user)
            return user
        return None

    def redirect_login_url(self):
        url = self.get_login_url()
        if "?" not in url:
            if urlparse.urlsplit(url).scheme:
                # if login url is absolute, make next absolute too
                next_url = self.request.full_url()
            else:
                next_url = self.request.uri
            url += "?" + urllib.urlencode(dict(next=next_url))
            self.redirect(url)

    def nonactive_behavior(self, user):
        if user.is_nonactive():
                    self.flash.error = "Your account has not been activated! Please check your register email box to get the activation link!"
                    self.redirect('/')


